package easy;

public class _125_ValidPalindrome {
    //测试用例过长，超时
    public boolean isPalindrome0(String s) {
        if(s.equals("")) return true;
        String trimS = "";
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(('a'<=c && c<='z') ||('A'<=c && c<='Z')){
                trimS+=Character.toLowerCase(c);
            }else if(('0'<=c && c<='9')){
                trimS+=c;
            }
        }
        if(trimS.equals("")) return true;
        int length =trimS.length();
        int lasPos = length-1;
        for(int i=0;i<length/2;i++){
            if(trimS.charAt(i)==trimS.charAt(lasPos)){
                lasPos--;
            }else{
                return false;
            }
        }
        return true;
    }
    //反转比较
    public boolean isPalindrome(String s) {
        //寻找非字母数字字符
        String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
        System.out.println(actual);
        String rev = new StringBuffer(actual).reverse().toString();
        System.out.println(rev);
        return actual.equals(rev);
    }
    //不复制，直接比较
    public boolean isPalindrome1(String s) {
        if (s.isEmpty()) {
            return true;
        }

        int head = 0;
        int tail = s.length() - 1;

        char cHead;
        char cTail;

        while(head <= tail) {
            cHead = s.charAt(head);
            cTail = s.charAt(tail);

            // 去除标点符号
            if (!Character.isLetterOrDigit(cHead)) {
                head++;
            } else if(!Character.isLetterOrDigit(cTail)) {
                tail--;
            } else {
                if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) {
                    return false;
                }

                head++;
                tail--;
            }
        }

        return true;
    }
}
